/**
 * Created by neal on 11/22/16.
 */

var Config = {
    createUrl: '/api/goods',
    updateUrl: '/api/goods',
    updateUrlForCellEdit: '/api/goods/cellEdit',
    deleteUrl: '/api/goods',
    selectUrl: '/api/warning/goods',
    selectCompanyUrl: '/api/admin/company/providers'

};
$().ready(function () {
    console.log("QAQ-----------------QAQ");
    $("#datepicker").datepicker({keyboardNavigation: !1, forceParse: !1, autoclose: !0});
    $.ajax(
        {
            url: Config.selectCompanyUrl,
            type: "GET",
            dataType: "json",
            async: false,
            success: function (data, textStatus, jqXHR) {
                var categories = [];
                categories.push('<option value="" hassubinfo="true">供货商</option>');
                data.data.map(function (company) {
                    categories.push('<option value="');
                    categories.push(company.companyId);
                    categories.push('" ');
                    categories.push('hassubinfo="true">');
                    categories.push(company.companyName);
                    categories.push('</option>');
                });
                $("#goodsProviderId").html(categories.join(''));
            },
            error: function (jqXHR, textStatus, errorThrown) {
                toastr.error(errorThrown, textStatus);
            }
        });
    $.ajax(
        {
            url: '/api/categories',
            type: "GET",
            dataType: "json",
            async: false,
            success: function (data, textStatus, jqXHR) {
                var categories = [];
                categories.push('<option value="" hassubinfo="true">全部分类</option>');
                data.data.map(function (category) {
                    categories.push('<option value="');
                    categories.push(category.categoryId);
                    categories.push('" ');
                    categories.push('hassubinfo="true">');
                    categories.push(category.categoryName);
                    categories.push('</option>');
                });
                $("#categoryId").html(categories.join(''));
            },
            error: function (jqXHR, textStatus, errorThrown) {
                toastr.error(errorThrown, textStatus);
            }
        });
    $.jgrid.defaults.styleUI = "Bootstrap";
    $("#data_list").jqGrid({
        datatype: "json",
        url: Config.selectUrl,
        height: 450,
        autowidth: true,
        shrinkToFit: true,
        rowNum: 12,
        colNames: ["编号", "商品名称", "库存","缩略图", "售价(元)", "进价(元)", "上架&下架","预警值", "操作"],
        colModel: [{
            name: "goodsId",
            index: "goodsId",
            autowidth: true,
            sorttype: "int",
            search: true
        }, {
            name: "goodsName",
            index: "goodsName",
            autowidth: true
        }, {
            name: "goodsStock",
            index: "goodsStock",
            autowidth: true,
            sorttype: "int"
        },  {
            name: "goodsThum",
            index: "goodsThum",
            autowidth: true,
            sorttype: "int"
        },{
            name: "goodsScreenPrice",
            index: "goodsScreenPrice",
            sorttype: "int",
            autowidth: true
        }, {
            name: "goodsRealPrice",
            index: "goodsRealPrice",
            sorttype: "int",
            autowidth: true
        }, {
            name: "goodsOnline",
            index: "goodsOnline",
            autowidth: true,
            editable: true,
            sortable: true,
            editoptions: {value: "0:下架;1:上架;2:仓库"},
            edittype: 'select',
            formatter: 'select'
        }, {
            name: "giveScore",
            index: "giveScore",
            autowidth: true,
            sorttype: "int"
        },
        //     {
        //     name: "goodsRecommendSort",
        //     index: "goodsRecommendSort",
        //     autowidth: true,
        //     editable: true,
        //     sortable: true
        // },
            {
            name: "operate",
            index: "operate",
            autowidth: true,
            sortable: false
        }],
        cellEdit: true,
        cellsubmit: 'remote',
        cellurl: Config.updateUrlForCellEdit,
        multiselect: true,
        multiboxonly: true,
        onSelectRow: function (id, status, e) {
            console.log($(e.target).parent().parent());
            // var item = $(e.target).parent().parent();
            // $(item).attr("aria-selected", "true");
            throw Error("");
        },
        beforeSelectRow: function (rowId, e) {
            // console.log("beforeSelectRow",rowId)
            return $(e.target).is('input[type=checkbox]');
        },
        pager: "#pager_data_list",
        jsonReader: {
            root: "data", "page": "page", total: "total",
            records: "records", repeatitems: false, id: "goodsId"
        },
        viewrecords: true,
        hidegrid: false,
        gridComplete: function () {
            //wrapper operate
            dataWrapper();
        }
    });
    $("#perform_search").click(function () {
        var postdata = $("#data_list").jqGrid('getGridParam', 'postData');
        postdata._search = true;
        postdata.categoryId = $('#categoryId option:selected').val();
        postdata.goodsPayType = $('#goodsPayType option:selected').val();
        postdata.goodsOnline = $('#goodsOnline option:selected').val();
        postdata.onlineGoods = $('#onlineGoods option:selected').val();
        postdata.goodsProviderType=$('#goodsProviderType option:selected').val();
        postdata.goodsProviderId=$('#goodsProviderId option:selected').val();
        postdata.goodsName = $('#textGoodsName').val();
        jQuery("#data_list").trigger("reloadGrid", [{page: 1}]);
    });
    jQuery("#data_list").jqGrid('navGrid', '#pager_data_list', {
        add: false,
        edit: false,
        del: false,
        search: true,
        refresh: true
    });
    $(window).bind("resize", function () {
        var width = $(".jqGrid_wrapper").width();
        $("#data_list").setGridWidth(width);
    });
});

function Delete(id) {
    updateDialog("DELETE", Config.deleteUrl + '/' + id, id);
}

function updateDialog(action, url, id) {
    $.ajax(
        {
            url: url,
            type: action,
            dataType: "json",
            success: function (data, textStatus, jqXHR) {
                if (action == 'DELETE') {
                    if (data && data.type == "SUCCESS") {
                        jQuery("#data_list").jqGrid('delRowData', id);
                        jQuery("#data_list").trigger("reloadGrid");
                    } else {
                        toastr.error(data.msg);
                    }
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                toastr.error("该角色下有关联的权限，请先删除.");
            }
        });
}
$("#batchSelect").change(function () {
    var selected = $(this).find("option:selected").val();
    if (selected == ""){
        return false;
    }
    if (selected == 1) {
        var goodsOnlineUp = jQuery("#data_list").jqGrid('getGridParam', 'selarrrow');
        if (goodsOnlineUp.length == 0){
            alert("请选择商品");
            return false;
        }
        for (var s = 0; s < goodsOnlineUp.length; s++) {
            console.log(s);
            $.ajax({
                url: Config.updateUrl,
                type: "PUT",
                data: {goodsId: goodsOnlineUp[s], goodsOnline: 1},
                dataType: "json",
                async: false,
                success: function (data, textStatus, jqXHR) {
                    toastr.success(data.msg, data.title);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    toastr.error(errorThrown, textStatus);
                }
            });

        }
    } else if (selected == 0) {
        var goodsOnlineDown = jQuery("#data_list").jqGrid('getGridParam', 'selarrrow');
        if (goodsOnlineDown.length == 0){
            alert("请选择商品");
            return false;
        }
        for (var y = 0; y < goodsOnlineDown.length; y++) {
            $.ajax({
                url: Config.updateUrl,
                type: "PUT",
                data: {goodsId: goodsOnlineDown[y], goodsOnline: 0},
                dataType: "json",
                async: false,
                success: function (data, textStatus, jqXHR) {
                    toastr.success(data.msg, data.title);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    toastr.error(errorThrown, textStatus);
                }
            });
        }
    } else if (selected == 999) {
        var ids = jQuery("#data_list").jqGrid('getGridParam', 'selarrrow');
        if (ids.length == 0){
            alert("请选择商品");
            return false;
        }
        for (var z = 0; z < ids.length; z++) {
            updateDialog("DELETE", Config.deleteUrl + '/' + ids[z], ids[z]);

        }
    }
    $("#batchSelect").val("");
    jQuery("#data_list").trigger("reloadGrid", [{page: 1}]);
});

$("#resetBut").click(function () {
    $("#batchSelect").val("").trigger("change");  //一行就搞定  红红火火恍恍惚惚哈哈哈哈哈哈
});

function dataWrapper() {
    var ids = jQuery("#data_list").jqGrid('getDataIDs');
    for (var i = 0; i < ids.length; i++) {
        var id = ids[i];
        var dataFromTheRow = jQuery('#data_list').jqGrid('getRowData', id);
        var avatar = '<img style="width: 50px; height: 50px;" src="'+dataFromTheRow.goodsThum+'"/>';
        var html = '<a class="J_menuItem" style="color:#f60;padding-right: 15px" href="/goods/update/' + id + '" data-index="0">编辑</a>';
        html += "<a style='color:#f60' onclick='Delete(" + id + ")' >删除</a>";
        var discount = (dataFromTheRow.goodsRealPrice/dataFromTheRow.goodsScreenPrice).toFixed(2)*100;
        if(isNaN(discount)){
            discount = 0;
        }else{
            discount = discount;
        }
        jQuery("#data_list").jqGrid('setRowData', ids[i], {
            operate: html,
            //goodsScreenPrice: toFixedForPrice((dataFromTheRow.goodsScreenPrice) / 100),
            //goodsRealPrice: toFixedForPrice((dataFromTheRow.goodsRealPrice) / 100),
            goodsScore: toFixedForScore((dataFromTheRow.goodsScore)),
            goodsScreenPrice: toFixedForScore((dataFromTheRow.goodsScreenPrice)),
            goodsRealPrice: toFixedForScore((dataFromTheRow.goodsRealPrice)),
            discount: discount,
            goodsThum:avatar
        });
    }
}
